import * as R from 'ramda';
import { Either, IO, Reader } from './vendor/ramda-fantasy';
import wxPackage from 'package-wx';
import { handleRequest } from 'handle-request';
import { turnPage } from 'turn-page';
const globalData = getApp().globalData;

const setFormData = e => Reader(that => that.setData({ [e.currentTarget.dataset.name]: e.detail.value }));
const trim = R.when(R.is(String), R.trim);
const trimForm = filterObj => R.compose(
  R.map(trim),
  R.when(() => R.is(Function, filterObj), filterObj)
);
const validate = wxValidate => R.ifElse(
  data => wxValidate.checkForm(data),
  Either.Right,
  () => Either.Left(wxValidate.errorList[0].msg)
);
const showError = errorMsg => IO(() => wx.showToast({
  icon: 'none',
  title: errorMsg,
  duration: 3000
}));
const handleError = either => Either.either(showError, IO.of, either);
const logout = () => IO(R.compose(
  () => wx.reLaunch({ url: '/pages/login/index' }),
  () => globalData.token = null,
  () => globalData.userInfo = null,
  () => wx.removeStorageSync('token'),
  () => wx.removeStorageSync('userInfo')
));
const reqPostShow = (api, successMsg) => data => handleRequest({
  isShowSuccessMsg: true,
  successMsg,
}, () => wxPackage.reqPost({
  url: api,
  data
}))
const backReqSuc = () => IO(
  //延迟返回是为了有时间显示提示
  () => setTimeout(wx.navigateBack, 1500)
);
// 不纯的函数//////////////////////////////////////////
const impure = {
  runIO: R.invoker(0, 'runIO'),
  run: R.invoker(1, 'run'),
  fork: R.invoker(2, 'fork')(R.identity, R.identity),
}


export default {
  ...wxPackage,
  ...impure,
  setFormData,
  trim,
  trimForm,
  validate,
  showError,
  handleError,
  handleRequest,
  turnPage,
  logout,
  reqPostShow,
  backReqSuc
}
